<template>
	<view class="map-container">
		<!-- 搜索栏 -->
		<view class="search-bar">
			<view class="search-input">
				<text class="iconfont icon-search"></text>
				<input 
					v-model="searchKey" 
					placeholder="输入地址搜索" 
					@input="handleInput"
					@confirm="handleSearch"
					@longpress="clearSearchKey"
				/>
				<text 
					class="iconfont icon-delete" 
					v-if="searchKey" 
					@click="clearSearchKey"
				></text>
			</view>
			<view class="search-btn" @click="handleSearch">搜索</view>
		</view>
		
		<!-- 联想提示 -->
		<view class="suggest-list" v-if="suggestList.length && searchKey && !searchResult.length">
			<view 
				class="suggest-item" 
				v-for="(item, index) in suggestList" 
				:key="index"
				@click="selectSuggest(item)"
			>
				<text class="suggest-name">{{ item.name }}</text>
				<text class="suggest-address">{{ item.address }}</text>
			</view>
		</view>
		
		<!-- 筛选条件区域 -->
		<view class="filter-bar">
			<view class="filter-item" @click="showCitySelector = true">
				<text>{{ selectedCity || '全国' }}</text>
				<text class="iconfont icon-down"></text>
			</view>
			<view class="filter-item" @click="showCategorySelector = true">
				<text>{{ selectedCategory.name || '全类别' }}</text>
				<text class="iconfont icon-down"></text>
			</view>
		</view>
		
		<!-- 搜索历史和热门搜索 -->
		<view class="search-history" v-if="!searchResult.length && !searchKey && (searchHistory.length || hotSearch.length)">
			<!-- 热门搜索 -->
			<view v-if="hotSearch.length">
				<view class="history-title">
					<text>热门搜索</text>
				</view>
				<view class="history-tags">
					<view 
						class="history-tag" 
						v-for="(item, index) in hotSearch" 
						:key="index"
						@click="searchKey = item; handleSearch()"
					>
						{{ item }}
					</view>
				</view>
			</view>
			
			<!-- 搜索历史 -->
			<view v-if="searchHistory.length">
				<view class="history-title">
					<text>搜索历史</text>
					<text class="iconfont icon-clear" @click="clearHistory"></text>
				</view>
				<view class="history-tags">
					<view 
						class="history-tag" 
						v-for="(item, index) in searchHistory" 
						:key="index"
					>
						<text @click="searchKey = item; handleSearch()">{{ item }}</text>
						<text class="iconfont icon-close" @click.stop="deleteHistory(index)"></text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 搜索结果列表 -->
		<view class="search-result" v-if="searchResult.length > 0">
			<view class="result-header">
				<text>找到 {{ searchResult.length }} 个结果</text>
			</view>
			<view 
				class="result-item" 
				v-for="(item, index) in searchResult" 
				:key="index"
				@click="selectAddress(item)"
			>
				<text class="title">{{ item.name }}</text>
				<text class="address">{{ item.address }}</text>
				<text class="category">{{ item.category }}</text>
			</view>
		</view>
		
		<!-- 无结果提示 -->
		<view class="no-result" v-if="showNoResult">
			<view class="no-result-icon">
				<text class="iconfont icon-search-fail"></text>
			</view>
			<view class="no-result-text">未找到匹配地址</view>
			<view class="no-result-guide">
				<text>试试更换关键词、城市或类别重新搜索</text>
			</view>
			<view class="no-result-recommend" v-if="nearbyRecommend.length">
				<view class="recommend-title">附近热门地点</view>
				<view 
					class="recommend-item" 
					v-for="(item, index) in nearbyRecommend" 
					:key="index"
					@click="selectAddress(item)"
				>
					{{ item.name }}
				</view>
			</view>
		</view>

		<!-- 地图容器 -->
		<view class="map-view">
			<map 
				:latitude="latitude" 
				:longitude="longitude" 
				:markers="markers" 
				:controls="controls"
				:show-location="true"
				:scale="mapScale"
				@markertap="onMarkerTap"
				@controltap="onControlTap"
				@regionchange="onRegionChange"
				style="width: 100%; height: 100%;"
			></map>
		</view>
		
		<!-- 底部操作栏 -->
		<view class="bottom-bar" v-if="selectedAddressInfo">
			<view class="action-btn" @click="startNavigation">
				<text class="iconfont icon-navigation"></text>
				<text>导航</text>
			</view>
			<view class="action-btn" @click="showRouteOptions = true">
				<text class="iconfont icon-route"></text>
				<text>路线</text>
			</view>
		</view>
		
		<!-- 城市选择器弹窗 -->
		<view class="selector-mask" v-if="showCitySelector" @click="showCitySelector = false"></view>
		<view class="selector-popup" v-if="showCitySelector">
			<view class="selector-title">选择城市</view>
			<view class="city-tabs">
				<view class="city-tab" :class="{active: cityTab === 'hot'}" @click="cityTab = 'hot'">热门</view>
				<view class="city-tab" :class="{active: cityTab === 'all'}" @click="cityTab = 'all'">全部</view>
			</view>
			<view class="city-list" v-if="cityTab === 'hot'">
				<view class="city-item" @click="selectCity('')">全国</view>
				<view class="city-item" @click="selectCity(item)" v-for="(item, index) in hotCities" :key="index">
					{{ item }}
				</view>
			</view>
			<view class="city-list" v-if="cityTab === 'all'">
				<view class="city-index">
					<view 
						class="index-item" 
						v-for="(key, index) in cityIndexs" 
						:key="index"
						@click="scrollToCity(key)"
					>
						{{ key }}
					</view>
				</view>
				<scroll-view class="city-scroll" :scroll-with-animation="true" :scroll-top="cityScrollTop">
					<view v-for="(group, key) in cityGroups" :key="key" :id="'city-' + key">
						<view class="city-group-title">{{ key }}</view>
						<view class="city-item" @click="selectCity(item)" v-for="(item, index) in group" :key="index">
							{{ item }}
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
		
		<!-- 类别选择器弹窗 -->
		<view class="selector-mask" v-if="showCategorySelector" @click="showCategorySelector = false"></view>
		<view class="selector-popup" v-if="showCategorySelector">
			<view class="selector-title">选择类别</view>
			<view class="category-list">
				<view class="category-item" @click="selectCategory({id: '', name: '全类别'})">全类别</view>
				<view class="category-group" v-for="(group, index) in categoryGroups" :key="index">
					<view class="category-group-title">{{ group.name }}</view>
					<view class="category-subitem" 
						v-for="(item, i) in group.subcategories" 
						:key="i"
						@click="selectCategory(item)"
					>
						{{ item.name }}
					</view>
				</view>
			</view>
		</view>
		
		<!-- 路线规划选项弹窗 -->
		<view class="selector-mask" v-if="showRouteOptions" @click="showRouteOptions = false"></view>
		<view class="selector-popup" v-if="showRouteOptions">
			<view class="selector-title">选择出行方式</view>
			<view class="route-options">
				<view class="route-option" @click="planRoute('driving')">
					<text class="iconfont icon-driving"></text>
					<text>驾车</text>
				</view>
				<view class="route-option" @click="planRoute('walking')">
					<text class="iconfont icon-walking"></text>
					<text>步行</text>
				</view>
				<view class="route-option" @click="planRoute('transit')">
					<text class="iconfont icon-bus"></text>
					<text>公交</text>
				</view>
			</view>
		</view>
		
		<!-- 路线规划结果弹窗 -->
		<view class="selector-mask" v-if="showRouteResult" @click="showRouteResult = false"></view>
		<view class="route-result-popup" v-if="showRouteResult">
			<view class="selector-title">
				<text>路线规划</text>
				<text class="iconfont icon-close" @click="showRouteResult = false"></text>
			</view>
			<view class="route-summary">
				<view class="route-distance">距离：{{ routeResult.distance || '未知' }}</view>
				<view class="route-duration">时间：{{ routeResult.duration || '未知' }}</view>
			</view>
			<view class="route-steps">
				<view class="step-item" v-for="(step, index) in routeResult.steps" :key="index">
					<view class="step-number">{{ index + 1 }}</view>
					<view class="step-content">{{ step.instruction }}</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
// 引入高德地图Web服务API（需替换为你的key）
// 注意：请确保你的API密钥已经开通了相关服务（如POI搜索、输入提示等）
const AMAP_KEY = "83400b74e47dc2663fa6c20301053fce"; // 从https://console.amap.com/申请

// 测试模式开关：开启后将使用模拟数据，方便调试
const TEST_MODE = false;

// 注意：请确保你的API密钥已经开通了相关服务（如POI搜索、输入提示等）
// 如果搜索失败，请检查密钥有效性和服务开通情况

// 模拟数据
const MOCK_SEARCH_RESULTS = [
  { name: '测试地点1', address: '北京市朝阳区测试路1号', lat: '39.90923', lng: '116.397428', category: '测试类别' },
  { name: '测试地点2', address: '北京市海淀区测试路2号', lat: '39.99923', lng: '116.337428', category: '测试类别' }
];
const MOCK_SUGGESTIONS = [
  { name: '测试提示1', address: '北京市朝阳区', lat: '39.90923', lng: '116.397428' },
  { name: '测试提示2', address: '北京市海淀区', lat: '39.99923', lng: '116.337428' }
];
const MOCK_NEARBY = [
  { name: '附近测试点1', address: '北京市朝阳区附近路1号', lat: '39.90923', lng: '116.397428' }
];


export default {
	data() {
		return {
			// 地图基本信息
			latitude: 39.90923,
			longitude: 116.397428,
			markers: [],
			controls: [
				{ id: 1, iconPath: "/static/images/zoom-in.png", position: { left: 20, top: 250, width: 40, height: 40 }, clickable: true },
				{ id: 2, iconPath: "/static/images/zoom-out.png", position: { left: 20, top: 300, width: 40, height: 40 }, clickable: true }
			],
			mapContext: null,
			mapScale: 16,
			
			// 搜索相关
			searchKey: "",
			searchResult: [],
			suggestList: [],
			showNoResult: false,
			selectedAddressInfo: null,
			
			// 筛选相关
			showCitySelector: false,
			showCategorySelector: false,
			selectedCity: '',
			selectedCategory: { id: '', name: '全类别' },
			cityTab: 'hot',
			cityScrollTop: 0,
			
			// 搜索历史和热门搜索（仅前端存储）
			searchHistory: [],
			hotSearch: ['天安门', '故宫博物院', '人民广场', '火车站', '机场', '购物中心'],
			
			// 路线规划相关
			showRouteOptions: false,
			showRouteResult: false,
			routeResult: {},
			
			// 附近推荐
			nearbyRecommend: [],
			
			// 城市数据（前端静态数据）
			hotCities: ['北京', '上海', '广州', '深圳', '杭州', '成都', '武汉', '南京', '重庆', '西安'],
			cityIndexs: ['A', 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'W', 'X', 'Y', 'Z'],
			cityGroups: {
				'A': ['安庆', '安阳', '鞍山'],
				'B': ['北京', '保定', '包头', '滨州'],
				'C': ['成都', '重庆', '长沙', '长春', '常州'],
				'D': ['大连', '东莞', '德州'],
				'F': ['福州', '佛山'],
				'G': ['广州', '贵阳', '桂林'],
				'H': ['杭州', '哈尔滨', '合肥', '海口'],
				'J': ['济南', '南京', '金华', '嘉兴'],
				'K': ['昆明', '开封'],
				'L': ['兰州', '洛阳', '临沂'],
				'M': ['绵阳', '茂名'],
				'N': ['南宁', '宁波', '南通'],
				'P': ['青岛', '莆田'],
				'Q': ['泉州', '秦皇岛'],
				'R': ['日照'],
				'S': ['上海', '深圳', '苏州', '沈阳'],
				'T': ['天津', '太原', '唐山'],
				'W': ['武汉', '无锡', '温州'],
				'X': ['西安', '厦门', '徐州'],
				'Y': ['烟台', '扬州', '宜昌'],
				'Z': ['郑州', '珠海', '湛江']
			},
			
			// 类别数据（前端静态数据）
			categoryGroups: [
				{
					name: '餐饮服务',
					subcategories: [
						{ id: '050100', name: '中餐' },
						{ id: '050200', name: '西餐' },
						{ id: '050300', name: '快餐' },
						{ id: '050400', name: '咖啡茶饮' },
						{ id: '050500', name: '火锅' }
					]
				},
				{
					name: '购物服务',
					subcategories: [
						{ id: '070100', name: '购物中心' },
						{ id: '070200', name: '超市' },
						{ id: '070300', name: '便利店' },
						{ id: '070400', name: '服装店' }
					]
				},
				{
					name: '交通出行',
					subcategories: [
						{ id: '150100', name: '火车站' },
						{ id: '150200', name: '机场' },
						{ id: '150300', name: '公交站' },
						{ id: '150400', name: '地铁站' }
					]
				},
				{
					name: '旅游住宿',
					subcategories: [
						{ id: '190100', name: '酒店' },
						{ id: '190200', name: '民宿' },
						{ id: '190300', name: '景点' },
						{ id: '190400', name: '公园' }
					]
				}
			]
		};
	},
	
	onLoad() {
		this.mapContext = uni.createMapContext('map', this);
		this.getCurrentLocation();
		
		// 从本地存储获取搜索历史（纯前端存储）
		this.searchHistory = uni.getStorageSync('amapSearchHistory') || [];
		
		// 从本地存储获取上次筛选条件（纯前端存储）
		const lastFilter = uni.getStorageSync('amapLastFilter') || {};
		if (lastFilter.city) this.selectedCity = lastFilter.city;
		if (lastFilter.category) this.selectedCategory = lastFilter.category;
	},
	
	methods: {
		// 获取当前位置
		getCurrentLocation() {
			uni.getLocation({
				type: 'gcj02',
				success: (res) => {
					this.latitude = res.latitude;
					this.longitude = res.longitude;
					this.mapContext.moveToLocation({ 
						latitude: res.latitude, 
						longitude: res.longitude,
						duration: 1000
					});
					this.addMarkerAtCurrentLocation();
					this.getCityInfo(res.longitude, res.latitude);
				},
				fail: (err) => {
					console.error('获取位置失败:', err);
					uni.showToast({ title: '获取位置失败，请检查权限', icon: 'none' });
				}
			});
		},
		
		// 获取当前城市信息
		getCityInfo(lng, lat) {
			uni.request({
				url: `https://restapi.amap.com/v3/geocode/regeo?key=${AMAP_KEY}&location=${lng},${lat}`,
				method: 'GET',
				success: (res) => {
					if (res.data.status === "1") {
						this.selectedCity = res.data.regeocode.addressComponent.city;
						this.saveFilterSettings();
					}
				}
			});
		},
		
		// 输入框变化时触发（用于联想提示）
		handleInput() {
			if (!this.searchKey.trim()) {
				this.suggestList = [];
				return;
			}
			
			// 如果是测试模式，使用模拟数据
			if (TEST_MODE) {
				this.suggestList = MOCK_SUGGESTIONS;
				return;
			}
			
			// 调用高德地图输入提示API
			uni.request({
				url: `https://restapi.amap.com/v3/assistant/inputtips?key=${AMAP_KEY}&keywords=${encodeURIComponent(this.searchKey)}&city=${this.selectedCity || ''}`,
				method: 'GET',
				timeout: 10000,
				success: (res) => {
					console.log('输入提示API响应:', res.data); // 添加调试日志
					if (res.data.status === "1" && res.data.tips.length > 0) {
						this.suggestList = res.data.tips.map(item => ({
							name: item.name,
							address: item.district + item.address,
							lat: item.location ? item.location.split(",")[1] : '',
							lng: item.location ? item.location.split(",")[0] : ''
						}));
					} else {
						this.suggestList = [];
						if (res.data.status !== "1") {
							console.error('输入提示API错误:', res.data.info);
						}
					}
				},
				fail: (err) => {
					console.error('输入提示请求失败:', err);
					this.suggestList = [];
				}
			});
		},
		
		// 处理搜索
		handleSearch() {
		    if (!this.searchKey.trim()) {
		      uni.showToast({ title: '请输入搜索关键词', icon: 'none' });
		      return;
		    }
		    
		    // 检查API密钥是否配置
		    if (AMAP_KEY === "你的高德地图Web服务key") {
		      uni.showModal({
		        title: '配置提示',
		        content: '请先在代码中配置你的高德地图API密钥',
		        showCancel: false
		      });
		      return;
		    }
		    
		    // 显示加载中提示
		    uni.showLoading({ title: '搜索中...' });
		    
		    // 如果是测试模式，使用模拟数据
		    if (TEST_MODE) {
		      setTimeout(() => {
		        uni.hideLoading();
		        this.searchResult = MOCK_SEARCH_RESULTS;
		        this.showNoResult = false;
		        this.nearbyRecommend = [];
		        
		        // 添加到搜索历史
		        this.addToHistory(this.searchKey);
		        
		        // 如果只有一个搜索结果，自动跳转到该位置
		        if (this.searchResult.length === 1) {
		          this.selectAddress(this.searchResult[0]);
		        }
		      }, 500);
		      return;
		    }
		    
		    // 构建搜索参数
		    let params = {
		      key: AMAP_KEY,
		      keywords: encodeURIComponent(this.searchKey),
		      output: 'json',
		      page: 1,
		      offset: 20
		    };
		    
		    // 添加城市筛选
		    if (this.selectedCity) {
		      params.city = this.selectedCity;
		    }
		    
		    // 添加类别筛选
		    if (this.selectedCategory.id) {
		      params.types = this.selectedCategory.id;
		    }
		    
		    // 构建查询字符串
		    const queryString = Object.keys(params)
		      .map(key => `${key}=${params[key]}`)
		      .join('&');
		    
		    // 调用高德地图POI搜索API
		    uni.request({
		      url: `https://restapi.amap.com/v3/place/text?${queryString}`,
		      method: 'GET',
		      timeout: 15000, // 增加超时时间到15秒
		      success: (res) => {
		        uni.hideLoading();
		        this.showNoResult = false;
		        this.nearbyRecommend = [];
		        
		        console.log('搜索API响应:', res.data); // 添加调试日志
		        
		        // 详细的错误状态处理
		        if (res.data.status !== "1") {
		          let errorMsg = "搜索失败: ";
		          switch(res.data.info) {
		            case "INVALID_USER_KEY":
		              errorMsg += "无效的API密钥，请检查你的密钥配置";
		              break;
		            case "USER_KEY_PLAT_NOMATCH":
              errorMsg += "API密钥与当前平台不匹配。请确保你的密钥适用于Web平台，并已开通相关服务（如POI搜索）。\n\n解决方法：\n1. 登录高德地图开放平台(https://console.amap.com/)\n2. 检查密钥的平台设置\n3. 确保已开通POI搜索等相关服务";
		              break;
		            case "OVER_QUERY_LIMIT":
		              errorMsg += "超出查询次数限制";
		              break;
		            case "INVALID_PARAMETERS":
		              errorMsg += "参数无效，请检查请求参数";
		              break;
		            case "SERVICE_NOT_AVAILABLE":
		              errorMsg += "服务当前不可用";
		              break;
		            default:
		              errorMsg += res.data.info || "未知错误";
		          }
		          uni.showToast({ title: errorMsg, icon: 'none', duration: 3000 });
		          return;
		        }
		        
		        if (res.data.pois.length > 0) {
		          // 格式化搜索结果
		          this.searchResult = res.data.pois.map(item => ({
		            name: item.name,
		            address: item.address || item.pname + item.cityname + item.adname + item.businessarea,
		            lat: item.location.split(",")[1],
		            lng: item.location.split(",")[0],
		            category: item.type.split(';')[0] || '未知类别',
		            poiId: item.id
		          }));
		          
		          // 添加到搜索历史
		          this.addToHistory(this.searchKey);
		          
		          // 如果只有一个搜索结果，自动跳转到该位置
		          if (this.searchResult.length === 1) {
		            this.selectAddress(this.searchResult[0]);
		          }
		        } else {
		          this.searchResult = [];
		          this.showNoResult = true;
		          this.getNearbyRecommend();
		        }
		      },
		      fail: (err) => {
		        uni.hideLoading();
		        console.error('搜索请求失败:', err);
		        
		        let errorMsg = "搜索失败: ";
		        if (err.errMsg.includes('timeout')) {
		          errorMsg += "请求超时，请稍后重试";
		          // 提供重试选项
		          uni.showModal({
		            title: '请求超时',
		            content: '网络请求超时，是否重试？',
		            success: (res) => {
		              if (res.confirm) {
		                this.handleSearch();
		              }
		            }
		          });
		          return;
		        } else if (err.errMsg.includes('network')) {
		          errorMsg += "网络连接异常，请检查网络后重试";
		        } else if (err.errMsg.includes('request:fail')) {
		          errorMsg += "请求失败，可能是API地址不正确或服务不可用";
		        } else {
		          errorMsg += "服务暂时不可用";
		        }
		        uni.showToast({ title: errorMsg, icon: 'none', duration: 3000 });
		      }
		    });
		  },
		
		// 获取附近推荐
		getNearbyRecommend() {
			// 如果是测试模式，使用模拟数据
			if (TEST_MODE) {
				this.nearbyRecommend = MOCK_NEARBY;
				return;
			}
			
			uni.request({
				url: `https://restapi.amap.com/v3/place/around?key=${AMAP_KEY}&location=${this.longitude},${this.latitude}&radius=2000&offset=5`,
				method: 'GET',
				timeout: 10000,
				success: (res) => {
					console.log('附近推荐API响应:', res.data); // 添加调试日志
					if (res.data.status === "1" && res.data.pois.length > 0) {
						this.nearbyRecommend = res.data.pois.map(item => ({
							name: item.name,
							address: item.address || item.pname + item.cityname + item.adname,
							lat: item.location.split(",")[1],
							lng: item.location.split(",")[0],
							poiId: item.id
						}));
					}
				},
				fail: (err) => {
					console.error('附近推荐请求失败:', err);
					this.nearbyRecommend = [];
				}
			});
		},
		
		// 选择联想提示项
		selectSuggest(item) {
			if (item.lat && item.lng) {
				this.selectAddress(item);
			} else {
				// 如果没有经纬度，使用关键词搜索
				this.searchKey = item.name;
				this.handleSearch();
			}
			this.suggestList = [];
		},
		
		// 选择地址并定位
		selectAddress(item) {
			// 验证经纬度有效性
			if (!item.lat || !item.lng || isNaN(Number(item.lat)) || isNaN(Number(item.lng))) {
				uni.showToast({ title: '地址位置信息无效', icon: 'none' });
				return;
			}
			
			// 转换为数字类型
			const targetLat = Number(item.lat);
			const targetLng = Number(item.lng);
			
			// 更新数据中心坐标
			this.latitude = targetLat;
			this.longitude = targetLng;
			
			// 平滑移动到目标位置
			this.mapContext.moveToLocation({ 
				latitude: targetLat, 
				longitude: targetLng,
				duration: 1000 
			});
			
			// 调整缩放级别
			this.mapScale = 18;
			
			// 保存选中的地址信息
			this.selectedAddressInfo = item;
			
			// 在选中地址添加标记
			this.markers = [{
				id: new Date().getTime(),
				latitude: targetLat,
				longitude: targetLng,
				title: item.name,
				iconPath: '/static/logo.png',
				width: 36,
				height: 36,
				callout: { 
					content: item.name, 
					color: '#fff', 
					bgColor: '#ff7d00', 
					display: 'ALWAYS',
					padding: 10,
					fontSize: 14
				}
			}];
			
			// 收起键盘
			uni.hideKeyboard();
			
			// 清空搜索结果和关键词
			this.searchResult = [];
			this.searchKey = "";
			this.suggestList = [];
			
			// 显示提示
			uni.showToast({ 
				title: `已定位到: ${item.name}`, 
				icon: 'none',
				duration: 1500
			});
		},
		
		// 添加到搜索历史（仅本地存储）
		addToHistory(keyword) {
			// 去重
			const index = this.searchHistory.indexOf(keyword);
			if (index > -1) {
				this.searchHistory.splice(index, 1);
			}
			
			// 添加到开头
			this.searchHistory.unshift(keyword);
			
			// 限制最多10条历史记录
			if (this.searchHistory.length > 10) {
				this.searchHistory.pop();
			}
			
			// 保存到本地存储（不涉及后端）
			uni.setStorageSync('amapSearchHistory', this.searchHistory);
		},
		
		// 清除搜索历史
		clearHistory() {
			uni.showModal({
				title: '提示',
				content: '确定要清除所有搜索历史吗？',
				success: (res) => {
					if (res.confirm) {
						this.searchHistory = [];
						uni.setStorageSync('amapSearchHistory', []);
					}
				}
			});
		},
		
		// 删除单条搜索历史
		deleteHistory(index) {
			this.searchHistory.splice(index, 1);
			uni.setStorageSync('amapSearchHistory', this.searchHistory);
		},
		
		// 清空搜索框
		clearSearchKey() {
			this.searchKey = "";
			this.suggestList = [];
		},
		
		selectCity(city) {
		  this.selectedCity = city;
		  this.showCitySelector = false;
		  this.saveFilterSettings();
		  
		  // 关键：选完城市后，重新执行搜索（如果有关键词）
		  if (this.searchKey.trim()) {
		    this.handleSearch(); 
		  } else {
		    // 无关键词时，更新地图中心到所选城市
		    this.updateMapToCity(city);
		  }
		},
		
		// 新增：根据城市名更新地图中心（调用高德 城市查询 API）
		updateMapToCity(cityName) {
		  uni.request({
		    url: `https://restapi.amap.com/v3/geocode/geo?key=${AMAP_KEY}&address=${cityName}`,
		    success: (res) => {
		      if (res.data.status === "1" && res.data.geocodes.length > 0) {
		        const location = res.data.geocodes[0].location.split(',');
		        this.latitude = Number(location[1]);
		        this.longitude = Number(location[0]);
		        this.mapContext.moveToLocation({ 
		          latitude: this.latitude, 
		          longitude: this.longitude,
		          duration: 1000 
		        });
		      } else {
		        uni.showToast({ title: '城市定位失败', icon: 'none' });
		      }
		    }
		  });
		},
		
		// 滚动到指定字母的城市组
		scrollToCity(key) {
			const query = uni.createSelectorQuery().in(this);
			query.select(`#city-${key}`).boundingClientRect(data => {
				this.cityScrollTop = data.top - 100; // 减去标题高度
			}).exec();
		},
		
		// 选择类别
		selectCategory(category) {
			this.selectedCategory = category;
			this.showCategorySelector = false;
			this.saveFilterSettings();
		},
		
		// 保存筛选设置（仅本地存储）
		saveFilterSettings() {
			uni.setStorageSync('amapLastFilter', {
				city: this.selectedCity,
				category: this.selectedCategory
			});
		},
		
		// 路线规划（纯前端调用地图API）
		planRoute(type) {
			this.showRouteOptions = false;
			uni.showLoading({ title: '规划路线中...' });
			
			// 获取当前位置作为起点
			uni.getLocation({
				type: 'gcj02',
				success: (res) => {
					const origin = `${res.longitude},${res.latitude}`;
					const destination = `${this.selectedAddressInfo.lng},${this.selectedAddressInfo.lat}`;
					let url = '';
					
					// 根据出行方式选择不同的API
					switch(type) {
						case 'driving':
							url = `https://restapi.amap.com/v3/direction/driving?key=${AMAP_KEY}&origin=${origin}&destination=${destination}`;
							break;
						case 'walking':
							url = `https://restapi.amap.com/v3/direction/walking?key=${AMAP_KEY}&origin=${origin}&destination=${destination}`;
							break;
						case 'transit':
							url = `https://restapi.amap.com/v3/direction/transit/integrated?key=${AMAP_KEY}&origin=${origin}&destination=${destination}&city=${this.selectedCity || ''}`;
							break;
					}
					
					uni.request({
						url: url,
						method: 'GET',
						success: (routeRes) => {
							uni.hideLoading();
							
							if (routeRes.data.status === "1" && routeRes.data.route) {
								// 处理不同类型的路线结果
								let steps = [];
								let distance = '';
								let duration = '';
								
								if (type === 'driving') {
									steps = routeRes.data.route.paths[0].steps;
									distance = this.formatDistance(routeRes.data.route.paths[0].distance);
									duration = this.formatDuration(routeRes.data.route.paths[0].duration);
								} else if (type === 'walking') {
									steps = routeRes.data.route.paths[0].steps;
									distance = this.formatDistance(routeRes.data.route.paths[0].distance);
									duration = this.formatDuration(routeRes.data.route.paths[0].duration);
								} else if (type === 'transit') {
									steps = routeRes.data.route.transits[0].segments.flatMap(segment => 
										segment.steps.map(step => ({ instruction: step.instruction }))
									);
									distance = this.formatDistance(routeRes.data.route.transits[0].distance);
									duration = this.formatDuration(routeRes.data.route.transits[0].duration);
								}
								
								this.routeResult = {
									steps: steps.map(step => ({ instruction: step.instruction })),
									distance,
									duration
								};
								
								this.showRouteResult = true;
							} else {
								uni.showToast({ title: '无法规划路线，请重试', icon: 'none' });
							}
						},
						fail: () => {
							uni.hideLoading();
							uni.showToast({ title: '路线规划失败', icon: 'none' });
						}
					});
				},
				fail: () => {
					uni.hideLoading();
					uni.showToast({ title: '无法获取当前位置', icon: 'none' });
				}
			});
		},
		
		// 格式化距离
		formatDistance(meters) {
			if (!meters) return '未知';
			meters = Number(meters);
			return meters >= 1000 ? (meters / 1000).toFixed(1) + '公里' : meters + '米';
		},
		
		// 格式化时间
		formatDuration(seconds) {
			if (!seconds) return '未知';
			seconds = Number(seconds);
			if (seconds < 60) return seconds + '秒';
			if (seconds < 3600) return Math.floor(seconds / 60) + '分钟';
			return Math.floor(seconds / 3600) + '小时' + Math.floor((seconds % 3600) / 60) + '分钟';
		},
		
		// 开始导航（打开高德地图APP）
		startNavigation() {
			uni.showModal({
				title: '导航',
				content: `是否打开高德地图导航至${this.selectedAddressInfo.name}？`,
				success: (res) => {
					if (res.confirm) {
						// 实际项目中可调用高德地图SDK的导航接口
						uni.showToast({ title: '正在打开导航...', icon: 'none' });
					}
				}
			});
		},
		
		// 添加当前位置标记
		addMarkerAtCurrentLocation() {
			this.markers = [{
				id: new Date().getTime(),
				latitude: this.latitude,
				longitude: this.longitude,
				title: '我的位置',
				iconPath: '/static/images/location-marker.png',
				width: 30,
				height: 30,
				callout: { 
					content: '我的位置', 
					color: '#fff', 
					bgColor: '#007aff', 
					display: 'ALWAYS' 
				}
			}];
		},
		
		// 地图控件点击事件
		onControlTap(e) {
			if (e.controlId === 1) {
				// 放大
				this.mapContext.getScale({
					success: (res) => {
						this.mapScale = res.scale + 1;
					}
				});
			} else if (e.controlId === 2) {
				// 缩小
				this.mapContext.getScale({
					success: (res) => {
						this.mapScale = res.scale - 1;
					}
				});
			}
		},
		
		// 地图区域变化事件
		onRegionChange(e) {
			// 拖动结束后更新中心坐标
			if (e.type === 'end') {
				this.mapContext.getCenterLocation({
					success: (res) => {
						this.latitude = res.latitude;
						this.longitude = res.longitude;
					}
				});
			}
		}
	}
};
</script>

<style scoped>
.map-container {
	width: 100%;
	height: 100vh;
	position: relative;
	background-color: #f5f5f5;
}

/* 搜索栏样式 */
.search-bar {
	position: absolute;
	top: 30rpx;
	left: 20rpx;
	right: 20rpx;
	display: flex;
	z-index: 999;
}

.search-input {
	flex: 1;
	display: flex;
	align-items: center;
	background-color: rgba(255, 255, 255, 0.95);
	border-radius: 60rpx;
	padding: 15rpx 30rpx;
	font-size: 28rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.search-input .icon-search {
	color: #666;
	margin-right: 15rpx;
	font-size: 32rpx;
}

.search-input .icon-delete {
	color: #999;
	margin-left: 15rpx;
	font-size: 28rpx;
}

.search-input input {
	flex: 1;
	height: 50rpx;
	line-height: 50rpx;
	color: #333;
}

.search-btn {
	width: 120rpx;
	height: 80rpx;
	line-height: 80rpx;
	text-align: center;
	background-color: #007aff;
	color: #ffffff;
	border-radius: 60rpx;
	margin-left: 20rpx;
	font-size: 28rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 122, 255, 0.3);
}

/* 联想提示样式 */
.suggest-list {
	position: absolute;
	top: 120rpx;
	left: 20rpx;
	right: 20rpx;
	background-color: rgba(255, 255, 255, 0.95);
	border-radius: 20rpx;
	z-index: 998;
	box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.1);
	max-height: 400rpx;
	overflow-y: auto;
}

.suggest-item {
	padding: 20rpx 30rpx;
	border-bottom: 1px solid #f0f0f0;
}

/* 筛选栏样式 */
.filter-bar {
	position: absolute;
	top: 120rpx;
	left: 20rpx;
	right: 20rpx;
	display: flex;
	background-color: rgba(255, 255, 255, 0.9);
	border-radius: 20rpx;
	z-index: 998;
}

.filter-item {
	flex: 1;
	height: 90rpx;
	line-height: 90rpx;
	text-align: center;
	font-size: 28rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #333;
	border-right: 1px solid #f0f0f0;
}

/* 搜索历史和热门搜索样式 */
.search-history {
	position: absolute;
	top: 210rpx;
	left: 20rpx;
	right: 20rpx;
	background-color: rgba(255, 255, 255, 0.95);
	border-radius: 20rpx;
	z-index: 997;
	box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.1);
	padding-bottom: 20rpx;
}

.history-title {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	font-size: 28rpx;
	color: #666;
}

.history-tags {
	padding: 0 30rpx;
	display: flex;
	flex-wrap: wrap;
	gap: 15rpx;
}

.history-tag {
	padding: 15rpx 25rpx;
	background-color: #f5f5f5;
	border-radius: 60rpx;
	font-size: 26rpx;
	color: #333;
	display: flex;
	align-items: center;
}

/* 搜索结果样式 */
.search-result {
	position: absolute;
	top: 210rpx;
	left: 20rpx;
	right: 20rpx;
	max-height: 500rpx;
	background-color: rgba(255, 255, 255, 0.95);
	border-radius: 20rpx;
	z-index: 997;
	overflow-y: auto;
}

.result-item {
	padding: 25rpx 30rpx;
	border-bottom: 1px solid #eee;
}

.result-item .title {
	font-size: 30rpx;
	color: #333;
	display: block;
	margin-bottom: 10rpx;
}

/* 无结果提示样式 */
.no-result {
	position: absolute;
	top: 210rpx;
	left: 20rpx;
	right: 20rpx;
	background-color: rgba(255, 255, 255, 0.95);
	border-radius: 20rpx;
	z-index: 997;
	padding: 60rpx 30rpx;
	text-align: center;
}

/* 地图容器样式 */
.map-view {
	width: 100%;
	height: 100%;
}

/* 底部操作栏样式 */
.bottom-bar {
	position: fixed;
	bottom: 30rpx;
	left: 0;
	right: 0;
	display: flex;
	justify-content: space-around;
	padding: 0 20rpx;
	z-index: 8;
}

.action-btn {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	width: 120rpx;
	height: 120rpx;
	background-color: #ffffff;
	border-radius: 50%;
	box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.1);
}

/* 选择器弹窗样式 */
.selector-mask {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 100;
}

.selector-popup {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #ffffff;
	border-top-left-radius: 30rpx;
	border-top-right-radius: 30rpx;
	z-index: 101;
	max-height: 80vh;
}

/* 城市和类别选择器样式 */
.city-tabs, .category-list, .route-options {
	padding: 20rpx;
}

.city-item, .category-item {
	height: 90rpx;
	line-height: 90rpx;
	padding-left: 30rpx;
	font-size: 28rpx;
	border-bottom: 1px solid #eee;
}

/* 路线规划样式 */
.route-result-popup {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #ffffff;
	border-top-left-radius: 30rpx;
	border-top-right-radius: 30rpx;
	z-index: 101;
	max-height: 80vh;
}

.route-steps {
	max-height: calc(80vh - 200rpx);
	overflow-y: auto;
}
</style>
    